package com.huike.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huike.core.domain.entity.SysUser;
import com.huike.dto.BusinessDto;
import com.huike.dto.BusinessRecordDto;
import com.huike.dto.GainClueDto;
import com.huike.dto.domain.Client;
import com.huike.dto.domain.TbBusiness;
import com.huike.mapper.BusinessRecordMapper;
import com.huike.mapper.TbBusinessMapper;
import com.huike.pojo.BusinessOpportunity;
import com.huike.pojo.ClueFollow;
import com.huike.pojo.OpportunityFollowUp;
import com.huike.result.PageResult;
import com.huike.service.BusinessService;
import com.huike.service.ClientService;
import com.huike.system.service.ISysUserService;
import com.huike.utils.SecurityUtils;
import com.huike.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class BusinessServiceImpl  extends ServiceImpl<TbBusinessMapper, TbBusiness> implements BusinessService {
    private final TbBusinessMapper tbBusinessMapper;
    private final ClientService clientService;
    private final ISysUserService sysUserService;
    private final BusinessRecordMapper businessRecordMapper;
    private final static String BEGIN="beginCreateTime";
    private final static String END="endCreateTime";
    private static final String FALSE_STATUS="3";//伪商机
    private final static String BUSINESS_NOT_FOLLOW_STATUS="1";//待跟进
    private final static String BUSINESS_FOLLOW_STATUS="2";//跟进中
    @Override
    public PageResult getBusinessListPage(BusinessDto businessDto) {
        Page<TbBusiness> page = new Page<>(businessDto.getPageNum(), businessDto.getPageSize());
        LambdaQueryWrapper<TbBusiness> wrapper = new LambdaQueryWrapper<>();
        String beginCreateTime = businessDto.getParams().get(BEGIN);
        String endCreateTime = businessDto.getParams().get(END);
        wrapper.eq(businessDto.getId()!=null,TbBusiness::getClueId,businessDto.getId());
        wrapper.eq(StringUtils.isNotEmpty(businessDto.getPhone()),TbBusiness::getPhone,businessDto.getPhone());
        wrapper.eq(StringUtils.isNotEmpty(businessDto.getOwner()),TbBusiness::getOwner,businessDto.getOwner());
        wrapper.eq(StringUtils.isNotEmpty(businessDto.getStatus()),TbBusiness::getStatus,businessDto.getStatus());
        if (StringUtils.isNotEmpty(beginCreateTime)&&StringUtils.isNotEmpty(endCreateTime)) {
            wrapper.between(TbBusiness::getCreateTime, beginCreateTime, endCreateTime);
        }
        wrapper.ne(TbBusiness::getStatus,FALSE_STATUS);
        Page<TbBusiness> res = super.page(page, wrapper);
        return new PageResult(res.getTotal(),res.getRecords());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBusiness(TbBusiness business) {
        //更新客户表
        Client client = new Client();
        BeanUtil.copyProperties(business,client);
        client.setStatus(null);
        clientService.save(client);
        business.setClientId(client.getId());
        business.setStatus(BUSINESS_NOT_FOLLOW_STATUS);
        tbBusinessMapper.insertTbBusiness(business);
    }

    @Override
    public void assignmentBusinessByIds(GainClueDto gainClueDto) {
        //批量分配
        SysUser user = sysUserService.selectUserById(gainClueDto.getUserId());
        LambdaUpdateWrapper<TbBusiness> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(TbBusiness::getId,gainClueDto.getIds())
                .set(TbBusiness::getOwner,user.getUserName())
                .set(TbBusiness::getAssignBy, SecurityUtils.getUsername())
                .set(TbBusiness::getOwnerTime,LocalDateTime.now());
        tbBusinessMapper.update(null,wrapper);
    }

    @Override
    public TbBusiness getBusinessById(Integer id) {
        return tbBusinessMapper.selectById(id);
    }

    @Override
    public List<OpportunityFollowUp> getBusinessRecordList(Integer businessId) {
        return businessRecordMapper.selectList(Wrappers.<OpportunityFollowUp>lambdaQuery().eq(OpportunityFollowUp::getBusinessId, businessId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBusinessRecord(BusinessRecordDto businessRecordDto) {
        //更新商机表，更近记录表
        businessRecordDto.setId(null);
        TbBusiness tbBusiness = new TbBusiness();
        BeanUtil.copyProperties(businessRecordDto,tbBusiness);
        tbBusiness.setId(businessRecordDto.getBusinessId());
        tbBusinessMapper.updateById(tbBusiness);
        OpportunityFollowUp follow = new OpportunityFollowUp();
        BeanUtil.copyProperties(businessRecordDto,follow);
        businessRecordMapper.insert(follow);
    }

    @Override
    public void backBusinesseById(Integer id, Integer reasons) {
        //转换成伪线索，status为3，新增操作记录
        TbBusiness tbBusiness = new TbBusiness();
        tbBusiness.setStatus(FALSE_STATUS);
        tbBusiness.setId(id.longValue());
        tbBusinessMapper.updateById(tbBusiness);
//        ClueFollow clueFollow = new ClueFollow();
//        clueFollow.setClueId(id);
//        clueFollow.setFalseReason(clueFalseDto.getReason());
//        clueFollow.setRecord(clueFalseDto.getRemark());
//        clueRecordMapper.insert(clueFollow);
    }

    @Override
    public void gainBusinessByIds(GainClueDto gainClueDto) {
        //批量捞取，从伪线索转化为线索,status为1,归属人更改，
        LambdaUpdateWrapper<TbBusiness> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(TbBusiness::getId,gainClueDto.getIds())
                .set(TbBusiness::getStatus,BUSINESS_NOT_FOLLOW_STATUS)
                .set(TbBusiness::getOwnerTime,LocalDateTime.now())
                .set(TbBusiness::getOwner,SecurityUtils.getUsername())
                .set(TbBusiness::getNextTime,null);
        tbBusinessMapper.update(null,wrapper);
    }

}
